package com.fire.job.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;


public class InitUtils {
	private static Log log = null;// 千万不要在这里初始化
	
	public static void init() {
		initLog4j();
		initPropertySet();
	}

	private static void initPropertySet() {
		Properties props = new Properties();
		try {
			String[] files = { "config/prop.properties", "config/prop.properties",
					"../config/prop.properties",
					"classpath:/config/prop.properties" };
			for (String file : files) {
				InputStream is = FileUtil.getStream(file);
				if (is != null) {
					props.load(is);
					IOUtils.closeQuietly(is);
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (props.size() > 0) {
			PropertyFactory.getInstance().setProperties(props);
			PropertyFactory.getInstance().save();
		} else {
			try {
                throw new Exception("Property Manager initial failed.");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
		}
	}

	
	/** 初始化log4j.properties，主要针对于log4j配置文件放在非默认位置的情况 */
	public static void initLog4j() {
		try {
			Class.forName("org.apache.log4j.PropertyConfigurator");
		} catch (ClassNotFoundException ex) {
			return;
		}
		Properties props = new Properties();
		try {
			String[] files = { "config/log4j.properties",
					"../config/log4j.properties", 
					"classpath:/config/log4j.properties" };
			for (String file : files) {
				InputStream is = FileUtil.getStream(file);
				if (is != null) {
					props.load(is);
					IOUtils.closeQuietly(is);
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (props.size() > 0) {
			PropertyConfigurator.configure(props);
		}
		log = LogFactory.getLog(InitUtils.class);
		log.info("log init ok!");
	}

	
}
